import React from 'react';
import './loginBox.less';
import API from "asha/libs/api.js"
import storage from "asha/libs/storage.js"
import url from "asha/libs/url.js"

var userStorage = storage("user.storage")
var apiStorage = new storage("api.storage")

class LoginBox extends React.Component {
    constructor(props) {
        super(props);
        this.displayName = 'LoginBox';
        this.state = {
            error:"",
            username:"",
            password:""
        }
    }
    handleChange(ele,event) {
        var newState={};
        newState[ele]=event.target.value;
        this.setState(newState);
    }
    submitHandler(e){
        e.preventDefault()
        var type = this.props.type
        API.callJson("/"+type+"/login")({
            telphone: this.state.username,
            password: this.state.password
        }).then((data)=>{
            //登录成功
            console.log(data)
            this.setState({
                error:null
            })
            userStorage.user = data.user
            apiStorage.getData().token = data.access.token
            userStorage.saveStorage();
            apiStorage.saveStorage();
            location.reload()
        }).catch((msg)=>{
            //登录失败
            console.log(msg)
            this.setState({
                error:msg
            })
        })
    }
    render() {
        return <div className="tederen-loginBox">
            <div className="login-container">
                <div className="head">
                    登录过期，请登录
                </div>
                <div className="body">
                    {this.state.error!=""?<div className="error-notice">
                        <span className="ion-close-circled"></span><span>{this.state.error}</span>
                    </div>:null}
                    <form onSubmit={this.submitHandler.bind(this)}>
                        <ul>
                            <li>
                                <input type="text" className="username" required placeholder="手机号"
                                value={this.state.username} onChange={this.handleChange.bind(this,'username')}/>
                            </li>
                            <li>
                                <input type="password" className="password" required placeholder="密码"
                                value={this.state.password} onChange={this.handleChange.bind(this,'password')}/>
                            </li>
                            <li>
                                <input type="submit" className="login-btn" value="登录"/>
                            </li>
                        </ul>
                    </form>
                </div>
            </div>
            <div className="login-mask"></div>
        </div>
    }
}

export default LoginBox
